package com.ruoyi.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.admin.domain.Login;
import com.ruoyi.admin.mapper.LoginMapper;
import com.ruoyi.admin.service.ILoginService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class LoginServiceImpl implements ILoginService {

    private final SysUserMapper sysUserMapper;


    @Override
    public AjaxResult login(Login login) {
        if (StringUtils.isBlank(login.getUsername())) {
            return AjaxResult.error("请输入用户名");
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", login.getUsername());
        Long userExist = sysUserMapper.selectCount(queryWrapper);
        if (userExist == 0) {
            return AjaxResult.error("用户不存在");
        }
        queryWrapper.eq("password", login.getPassword());
        SysUser userInfo = sysUserMapper.selectOne(queryWrapper, false);
        if (userInfo != null) {
            if ("1".equals(userInfo.getStatus())) {
                return AjaxResult.error("账号已被停用");
            }
            if ("2".equals(userInfo.getDelFlag())) {
                return AjaxResult.error("账号不存在");
            }
            StpUtil.login(userInfo.getUserId());
            StpUtil.getSession().set("user", userInfo);
            String tokenValue = StpUtil.getTokenValue();
            return AjaxResult.success(tokenValue);
        }
        return AjaxResult.error("密码错误");
    }
}
